package com.hzh.audioflutter.my_audio_recorder;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.text.format.DateFormat;

import java.io.File;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;

import io.flutter.Log;

public class AudioRecordService extends Service {

    private NotificationManager manager;
    private Notification.Builder builder;

    private MediaRecorder mMediaRecorder;
    private String audioName;
    private File audioFile;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("TAG_ME", "进入onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 开始录音
        Log.e("TAG_ME", "进入onStartCommand");
        String action = intent.getStringExtra(RecordState.RECORD_ACTION);
        if (action == null) {
            return super.onStartCommand(intent, flags, startId);
        }
        switch (action) {
            case RecordState.RECORD_ACTION_START:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    // android 8.0之后
                    String NOTIFICATION_CHANNEL_ID = "录音";
                    String channelName = "录音服务";
                    NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_LOW);
                    manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    manager.createNotificationChannel(channel);
                    //开启另一个页面
                    builder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
                            .setWhen(System.currentTimeMillis())  // the time stamp
                            .setSmallIcon(R.drawable.anew)
                            .setContentText("正在录音中...");  // the contents of the entry
                    Notification notification = builder.build();
                    manager.notify(1, notification);
                    startForeground(1, notification);
                }
                startRecord();
                break;
            case RecordState.RECORD_ACTION_CONTINUE:
                continueRecord();
                break;
            case RecordState.RECORD_ACTION_PAUSE:
                pauseRecord();
                break;
            case RecordState.RECORD_ACTION_STOP:
                stopRecord();
                // 关闭Service
                stopSelf();
                break;
        }
        return START_STICKY;
    }

    private void startRecord() {
        // 权限具备
        if (mMediaRecorder == null) {
            Log.e("TAG_ME", "startRecord 1");
            mMediaRecorder = new MediaRecorder();
        }
        try {
            mMediaRecorder.reset();
            // 设置录音配置
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setAudioSamplingRate(16000); // 16K
            mMediaRecorder.setAudioEncodingBitRate(16 * 1024); // 16
            mMediaRecorder.setAudioChannels(1); // 单
            audioName = DateFormat.format("MM月dd日HH点mm分" + new Random().nextInt(85468), Calendar.getInstance(Locale.CHINA)) + ".mp3";
//            audioFile = new File(getExternalCacheDir() + "/" + audioName);
            audioFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + audioName);
            // 准备录音
            mMediaRecorder.setOutputFile(audioFile.getAbsolutePath());
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            // 正在录音
//            sendMessage(RecordState.RECORDING, "");
        } catch (Exception e) {
            Log.e("TAG_ME", "startRecord 3 " + e);
        }
    }

    private String continueRecord() {
        if (mMediaRecorder == null) {
            return "";
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mMediaRecorder.resume();
        }
        return "success";
    }

    private String pauseRecord() {
        if (mMediaRecorder == null) {
            return "";
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mMediaRecorder.pause();
        }
        return "success";
    }

    private String stopRecord() {
        try {
            if (mMediaRecorder != null) {
                mMediaRecorder.stop();
                mMediaRecorder.release();
                mMediaRecorder = null;
                Log.e("TAG_ME", "stopRecord 1");
                Log.e("TAG_ME", "结束录音，file path：" + audioFile.getAbsolutePath());
                sendMessage(RecordState.RECORD_ACTION_OVER, audioFile.getAbsolutePath());
                return "success";
            } else {
                Log.e("TAG_ME", "stopRecord 2");
                return "";
            }
        } catch (Exception e) {
            Log.e("TAG_ME", "stopRecord 3 " + e);
            return "";
        }
    }

    private void sendMessage(String state, String filePath) {
        Intent intent = new Intent(RecordState.RECORD_BROADCAST_ACTION);
        intent.putExtra(RecordState.RECORD_BROADCAST_ACTION, state);
        intent.putExtra(RecordState.RECORD_BROADCAST_FILE_PATH, filePath);
        sendBroadcast(intent);
    }
}
